package MultiThread;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {

    //类似于限流器
    private static Semaphore semaphore = new Semaphore(2);

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            System.out.println("可用"+semaphore.availablePermits());
            new Thread(new Worker(semaphore, i)).start();
        }
    }
}

class Worker implements Runnable{

    private Semaphore s;

    private int i;

    public Worker(Semaphore s, int i) {
        this.s = s;
        this.i = i;
    }

    @Override
    public void run() {
        try {
            s.acquire();
            System.out.println("排队"+s.getQueueLength());

            System.out.println("thread " + i + " start...");
            Thread.sleep(i * 1000);
            System.out.println("thread " + i + " end...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            s.release();
        }
    }
}
